package com.frxuexi.sign.view

import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.navigation.NavHostController
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.CoordType
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.R
import com.frxuexi.lib_base.UiState
import com.frxuexi.sign.SignIntent
import com.frxuexi.sign.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Timer
import kotlin.concurrent.timerTask


lateinit var timer: Timer
lateinit var mapView:MapView
lateinit var map:BaiduMap
lateinit var mLocationClient:LocationClient
@Composable
fun SignPage(navHostController: NavHostController,vm:SignViewModel= hiltViewModel()) {
    var time by remember {
        mutableStateOf(SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis()))
    }
    val kv = MMKV.defaultMMKV()

    var btnSign by remember {
        mutableStateOf("签到")
    }

    var startTime by remember {
        mutableStateOf("还未打卡")
    }

    var endTime by remember {
        mutableStateOf("还未打卡")
    }

    var enable by remember {
        mutableStateOf(true)
    }

    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(key1 = "", effect = {

        val observer = LifecycleEventObserver { _, event ->
            when(event){
                Lifecycle.Event.ON_CREATE->{
                    Log.i("===","oncreate")
                }
                Lifecycle.Event.ON_RESUME->{
                    Log.i("===","ON_RESUME")
                }
                Lifecycle.Event.ON_START->{
                    Log.i("===","ON_START")
                }
                Lifecycle.Event.ON_PAUSE->{
                    Log.i("===","ON_PAUSE")
                }
                Lifecycle.Event.ON_STOP->{
                    Log.i("===","ON_STOP")
                }
                Lifecycle.Event.ON_DESTROY->{
                    Log.i("===","ON_DESTROY")
                }

                else -> {}
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            Log.i("===","onDispose")
            timer.cancel()
            mLocationClient.stop();
            map.setMyLocationEnabled(false);
            mapView.onDestroy();
        }
    })

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ToastUtils.showLong("打卡成功")
                    }

                    else -> {}
                }
            }
        }

        launch {
            timer= Timer()
            timer.schedule(timerTask {
                      time=SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            },0,1000)
        }

        launch {
            //页面进来获取签到时间
            val signTime = kv.decodeString("sign", "").toString()
            //如果签到有值
            if(!TextUtils.isEmpty(signTime)){
                //获取今天的日期
                val today = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                //说明今天签到过
                if(signTime.substring(0,10)==today){
                    //展示签到时间
                    startTime=signTime
                    //获取签退时间
                    val soutTime = kv.decodeString("sout", "").toString()
                    //从来没有签退过或者部署今天签退的
                    if(soutTime.isNullOrEmpty() || soutTime.substring(0,10)!=today){
                        //该做签退工作
                        btnSign="签退"
                    }else{
                        //今天打过签退
                        enable=false
                        endTime=soutTime
                    }
                }
            }
        }
    })


    Column {
        BaseTitle(title = "打卡", navHostController = navHostController)
        initMap()
        AndroidView(modifier = Modifier
            .fillMaxWidth()
            .height(260.dp), factory = {
            mapView = MapView(it)
            map = mapView.map
            map.setMyLocationEnabled(true);
            mapView
        })
        Spacer(modifier = Modifier.height(20.dp))
        Text(text = "上班时间：$startTime",Modifier.padding(horizontal = 20.dp))
        Spacer(modifier = Modifier.height(20.dp))
        Text(text = "下班时间：$endTime",Modifier.padding(horizontal = 20.dp))
        Spacer(modifier = Modifier.height(20.dp))
        Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
            Button(modifier = Modifier.size(150.dp), enabled = enable, colors = ButtonDefaults.buttonColors(containerColor = colorResource(
                id = R.color.blue
            )),onClick = {
                val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                if(btnSign=="签到"){
                    btnSign="签退"
                    startTime=time
                    kv.encode("sign",time)
                }else{
                    endTime=time
                    kv.encode("sout",time)
                    enable=false
                }
                val map = mutableMapOf<String, Any>()
                map["userId"]=1
                map["SignLat"]=kv.decodeFloat("latitude",0f)
                map["SignLong"]=kv.decodeFloat("longitude",0f)
                map["signTime"]=System.currentTimeMillis()
                vm.sendIntent(SignIntent.sign(map))
            }) {
                Column(modifier = Modifier.size(150.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(text = btnSign, fontSize = 22.sp)
                    Spacer(modifier = Modifier.height(20.dp))
                    Text(text = time, fontSize = 22.sp)
                }
            }
        }

    }
}

fun initMap() {
    LocationClient.setAgreePrivacy(true);
    SDKInitializer.setAgreePrivacy(BaseApp.context,true)
    //在使用SDK各组件之前初始化context信息，传入ApplicationContext
    SDKInitializer.initialize(BaseApp.context);
    //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
    //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
    SDKInitializer.setCoordType(CoordType.BD09LL);

    //定位初始化
    //定位初始化
    mLocationClient = LocationClient(BaseApp.context)

//通过LocationClientOption设置LocationClient相关参数

//通过LocationClientOption设置LocationClient相关参数
    val option = LocationClientOption()
    option.isOpenGps = true // 打开gps

    option.setCoorType("bd09ll") // 设置坐标类型

    option.setScanSpan(1000)

//设置locationClientOption

//设置locationClientOption
    mLocationClient.setLocOption(option)

//注册LocationListener监听器

//注册LocationListener监听器
    val myLocationListener = MyLocationListener()
    mLocationClient.registerLocationListener(myLocationListener)
//开启地图定位图层
//开启地图定位图层
    mLocationClient.start()
}


class MyLocationListener : BDAbstractLocationListener() {
    override fun onReceiveLocation(location: BDLocation) {
        //mapView 销毁后不在处理新接收的位置
        if (location == null || mapView == null) {
            return
        }
        val latitude = location.latitude
        val longitude = location.longitude

        val kv = MMKV.defaultMMKV()
        kv.encode("latitude",latitude)
        kv.encode("longitude",longitude)

        //定位蓝点额外加的
        var ll = LatLng(latitude, longitude);
        val update = MapStatusUpdateFactory.newLatLngZoom(ll, 5f);
        map.animateMapStatus(update);

        val locData = MyLocationData.Builder()
            .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(location.direction).latitude(latitude)
            .longitude(longitude).build()
        map.setMyLocationData(locData)
    }
}
